package com.bootdo.ztzb.controller;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.*;

import org.activiti.engine.task.Task;
import com.bootdo.activiti.vo.TaskVO;
import com.bootdo.activiti.controller.TaskController;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.bootdo.activiti.service.impl.ActTaskServiceImpl;
import com.bootdo.activiti.utils.ActivitiUtils;
import org.activiti.engine.TaskService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.system.service.DeptService;
import com.bootdo.util.IdWorker;
import com.bootdo.util.SnowflakeIdWorkerUtil;
import com.bootdo.util.UserUtil;
import org.apache.poi.ss.usermodel.Workbook;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.bootdo.common.utils.text.StringUtils;
import com.bootdo.system.domain.DeptDO;
import org.apache.poi.ss.usermodel.Workbook;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bootdo.common.utils.DateUtils;

import com.bootdo.ztzb.domain.ZtzbProcessProductDO;
import com.bootdo.ztzb.service.ZtzbProcessProductService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.FileUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.stream.Collectors;

/**
 * 产品信息
 *
 * @author admin
 * @email ${email}
 * @date 2025-10-15
 */

@Controller
@RequestMapping("/ztzb/ztzbProcessProduct")
public class ZtzbProcessProductController {
    @Autowired
    private ZtzbProcessProductService ztzbProcessProductService;

    @Autowired
    private BootdoConfig bootdoConfig;

    @Autowired
    private DeptService deptService;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    @Autowired
    ActivitiUtils activitiUtils;

    @Autowired
    TaskService taskService;

    @Autowired
    TaskController taskController;

    /**
     * 导入产品信息
     *
     * @param file
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/importZtzbProcessProductData")
    @RequiresPermissions("ztzb:ztzbProcessProduct:importColumn")
    R importZtzbProcessProductData(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String fileName = file.getOriginalFilename();
        String fileNameOriginal = fileName;
        fileName = FileUtil.renameToUUID(fileName);
        String date = com.bootdo.util.DateUtils.format(new Date());
        try {
            // 上传文件
            FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath() + date + "/", fileName);
//                if (!fileNameOriginal.contains("桥梁媒体导入模板")) {
//                    return R.error("文件模板名称错误，请下载模板!");
//                }
            List<ZtzbProcessProductDO> ztzbProcessProductDOS = importExcel(bootdoConfig.getUploadPath() + date + "/" + fileName, 1, 1, ZtzbProcessProductDO.class);
            return importZtzbProcessProduct(ztzbProcessProductDOS);
        } catch (Exception e) {
            return R.error();
        }
    }


    public <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return list;
    }


    /**
     * 导入产品信息数据
     *
     * @param ztzbProcessProductDOS
     * @return
     */
    private R importZtzbProcessProduct(
    List<ZtzbProcessProductDO> ztzbProcessProductDOS)

    {
        if (ztzbProcessProductDOS.size() > 0) {
            for (ZtzbProcessProductDO ztzbProcessProductDO : ztzbProcessProductDOS) {
//                if (StringUtils.isNotBlank(ztzbProcessProductDO.getDepartment())) {
//                    SnowflakeIdWorkerUtil idWorker = new SnowflakeIdWorkerUtil(1, 1);
//                        ztzbProcessProductDO.setMediaId(idWorker.nextId() + "");
//                        ztzbProcessProductDO.setCreateDatetime(new Date());
//                        ztzbProcessProductDO.setUpdateDatetime(new Date());
//                        ztzbProcessProductDO.setDelFlag("0");
//                    DeptDO deptDO = deptService.get(UserUtil.getUserDO().getDeptId());
//                        ztzbProcessProductDO.setFillDepart(deptDO.getName());
//                        ztzbProcessProductDO.setFillDepartId(deptDO.getDeptId().toString());
//                        ztzbProcessProductDO.setFillUser(UserUtil.getUserDO().getUsername());
//                        ztzbProcessProductDO.setFillUserId(UserUtil.getUserDO().getUserId().toString());
//                        ztzbProcessProductDO.setSpare1("未使用");
                    ztzbProcessProductService.save(ztzbProcessProductDO);
//                }
            }
        }
        return R.ok();
    }

    /**
     * 下载产品信息
     */
    @RequestMapping("/downLoadZtzbProcessProductData")
    @ResponseBody
    @RequiresPermissions("ztzb:ztzbProcessProduct:importColumn")
    void downLoadZtzbProcessProductData(String type, HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {
        List<ZtzbProcessProductDO> ztzbProcessProductDOS = ztzbProcessProductService.list(params);
        List<ZtzbProcessProductDO> ztzbProcessProductDOS1 = new ArrayList<>();
        if (ztzbProcessProductDOS.size() > 0) {
                ztzbProcessProductDOS1.add(ztzbProcessProductDOS.get(0));
        }
        String title = "产品信息模板";
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, null),
            ZtzbProcessProductDO.class, ztzbProcessProductDOS1);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(title, "utf-8") + ".xls");
        workbook.write(response.getOutputStream());
        workbook.close();
    }


    /**
    * 导出
    */
    @RequestMapping("/exportColumn")
    @ResponseBody
    @RequiresPermissions("ztzb:ztzbProcessProduct:exportColumn")
    void exportColumn(String type, HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {
        List<ZtzbProcessProductDO> ztzbProcessProductDOS = ztzbProcessProductService.list(params);
        String title = "产品信息" + DateUtils.format(new Date());
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, null),
            ZtzbProcessProductDO.class, ztzbProcessProductDOS);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(title, "utf-8") + ".xls");
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    @GetMapping()
    @RequiresPermissions("ztzb:ztzbProcessProduct:ztzbProcessProduct")
    String ZtzbProcessProduct() {
        return "ztzb/ztzbProcessProduct/ztzbProcessProduct";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("ztzb:ztzbProcessProduct:ztzbProcessProduct")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ZtzbProcessProductDO> ztzbProcessProductList = ztzbProcessProductService.list(query);
        List<TaskVO> taskVOS = taskController.todoList();
        Set<String> taskIds = taskVOS.stream()
                .map(TaskVO::getId)
                .collect(Collectors.toSet());
            ztzbProcessProductList.forEach(product -> {
            if (taskIds.contains(product.getProcessTaskId())) {
                product.setApplyStatus(0);  // Can be approved
            } else {
                product.setApplyStatus(1);  // Cannot be approved
            }
        });
        int total = ztzbProcessProductService.count(query);
        PageUtils pageUtils = new PageUtils(ztzbProcessProductList, total);
        return pageUtils;
    }

    /**
 *  产品信息下拉数据
 * @param params
 * @return
 */
    @ResponseBody
    @GetMapping("/ztzbProcessProductList")
    @RequiresPermissions("ztzb:ztzbProcessProduct:ztzbProcessProduct")
    public List<ZtzbProcessProductDO> ztzbProcessProductList(@RequestParam Map<String, Object> params){
        List<ZtzbProcessProductDO> ztzbProcessProductList = ztzbProcessProductService.list(params);
        return ztzbProcessProductList;
    }

    @GetMapping("/add")
    @RequiresPermissions("ztzb:ztzbProcessProduct:add")
    String add() {
        return "ztzb/ztzbProcessProduct/add";
    }

    @GetMapping("/apply")
    @RequiresPermissions("ztzb:ztzbProcessProduct:apply")
    String applyAdd() {
        return "ztzb/ztzbProcessProduct/add";
    }

    /**
    * 审批前置
 * @param taskId
 * @param model
 * @return
*/
    @GetMapping("/apply/{taskId}")
    @RequiresPermissions("ztzb:ztzbProcessProduct:apply")
    String apply(@PathVariable("taskId") String taskId, Model model) {
            ZtzbProcessProductDO ztzbProcessProduct = ztzbProcessProductService.get(Long.valueOf(activitiUtils.getBusinessKeyByTaskId(taskId)));
        ztzbProcessProduct.setTaskId(taskId);
        model.addAttribute("ztzbProcessProduct", ztzbProcessProduct);
        return "ztzb/ztzbProcessProduct/apply";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("ztzb:ztzbProcessProduct:edit")
    String edit(@PathVariable("id") Long id, Model model) {
            ZtzbProcessProductDO ztzbProcessProduct = ztzbProcessProductService.get(id);
        model.addAttribute("ztzbProcessProduct", ztzbProcessProduct);
        return "ztzb/ztzbProcessProduct/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("ztzb:ztzbProcessProduct:add")
    public R save( ZtzbProcessProductDO ztzbProcessProduct) {
        IdWorker idWorker = new IdWorker();
        // ztzbProcessProduct.setUuid(idWorker.nextId() + "");
        if (ztzbProcessProductService.save(ztzbProcessProduct) > 0) {
            try {
                String proId = actTaskService.startProcess("ztzbProcessProduct",
                        "ztzbProcessProduct", String.valueOf(ztzbProcessProduct.getId()),
                ztzbProcessProduct.getContent(), new HashMap<>());
                List<Task> tasks = taskService.createTaskQuery().processInstanceId(proId).list();
                if (tasks.size() > 0) {
                    Task task = tasks.get(0);
                    ztzbProcessProduct.setAssignee(task.getAssignee());
                    ztzbProcessProduct.setProcInsId(task.getProcessInstanceId());
                    ztzbProcessProduct.setTaskName(task.getName());
                    ztzbProcessProduct.setProcessTaskId(task.getId());
                        ztzbProcessProductService.update(ztzbProcessProduct);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("流程不存在");
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("ztzb:ztzbProcessProduct:edit")
    public R update( ZtzbProcessProductDO ztzbProcessProduct) {
        if (StringUtils.isNotBlank(ztzbProcessProduct.getTaskId())) {

            Map<String, Object> vars = new HashMap<>(16);
            vars.put("pass",  ztzbProcessProduct.getTaskPass() );
            vars.put("title", "");
            actTaskService.complete(ztzbProcessProduct.getTaskId(), vars);
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(ztzbProcessProduct.getProcInsId()).
                    list();
            if (tasks.size() > 0) {
                Task task = tasks.get(0);
                ztzbProcessProduct.setAssignee(task.getAssignee());
                ztzbProcessProduct.setTaskName(task.getName());
                ztzbProcessProduct.setProcessTaskId(task.getId());
            } else {
                if (StringUtils.isNotBlank(ztzbProcessProduct.getTaskPass()) && "0".equals
                        (ztzbProcessProduct.getTaskPass())){
                    ztzbProcessProduct.setAssignee(null);
                    ztzbProcessProduct.setTaskName("已取消");
                }else{
                    ztzbProcessProduct.setAssignee(null);
                    ztzbProcessProduct.setTaskName("审核完成");
                }
            }

        }
            ztzbProcessProductService.update(ztzbProcessProduct);
        return R.ok();
    }

    /**
     * 审批
     */
    @ResponseBody
    @RequestMapping("/applyUpdate")
    @RequiresPermissions("ztzb:ztzbProcessProduct:apply")
    public R applyUpdate( ZtzbProcessProductDO ztzbProcessProduct) {
        Map<String, Object> vars = new HashMap<>(16);
        vars.put("pass",  ztzbProcessProduct.getTaskPass() );
        vars.put("title", "");
        actTaskService.complete(ztzbProcessProduct.getTaskId(), vars);
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(ztzbProcessProduct.getProcInsId()).
        list();
        if (tasks.size() > 0) {
            Task task = tasks.get(0);
            ztzbProcessProduct.setAssignee(task.getAssignee());
            ztzbProcessProduct.setTaskName(task.getName());
            ztzbProcessProduct.setProcessTaskId(task.getId());
        } else {
            ztzbProcessProduct.setAssignee(null);
            ztzbProcessProduct.setTaskName("审核完成");
        }
            ztzbProcessProductService.update(ztzbProcessProduct);
        return R.ok();
    }

    @GetMapping("/review/{id}")
    @RequiresPermissions("ztzb:ztzbProcessProduct:review")
    String review(@PathVariable("id") Long id, Model model) {
            ZtzbProcessProductDO ztzbProcessProduct = ztzbProcessProductService.get(id);
        model.addAttribute("ztzbProcessProduct", ztzbProcessProduct);
        return "ztzb/ztzbProcessProduct/review";
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("ztzb:ztzbProcessProduct:remove")
    public R remove( Long id) {
        if (ztzbProcessProductService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("ztzb:ztzbProcessProduct:batchRemove")
    public R remove(@RequestParam("ids[]") Long[] ids) {
            ztzbProcessProductService.batchRemove(ids);
        return R.ok();
    }

}
